package com.zenithmind.gateway.exception;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * ResponseStatusException处理策略
 * 专门处理ResponseStatusException类型的异常
 * 遵循策略模式：实现特定异常类型的处理算法
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ResponseStatusExceptionStrategy implements ExceptionHandlingStrategy {
    
    private final ErrorResponseBuilder errorResponseBuilder;

    @Override
    public boolean canHandle(Throwable ex) {
        return ex instanceof ResponseStatusException;
    }

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ResponseStatusException responseStatusException = (ResponseStatusException) ex;

        log.warn("处理ResponseStatusException: {}", responseStatusException.getReason());

        return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
            // 将HttpStatusCode转换为HttpStatus
            HttpStatus httpStatus = HttpStatus.valueOf(responseStatusException.getStatusCode().value());

            errorResponseBuilder.setResponseHeaders(exchange.getResponse(), httpStatus);

            DataBuffer buffer = errorResponseBuilder.buildErrorResponse(
                exchange.getResponse(),
                httpStatus,
                responseStatusException.getReason(),
                ex
            );

            return buffer;
        }));
    }

    @Override
    public int getOrder() {
        return 1; // 较高优先级，优先处理ResponseStatusException
    }
}
